package com.oa.tools.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.oa.tools.utils.DateUtil;
import com.oa.tools.utils.http.HttpUtil;

public class AccessInterceptor implements HandlerInterceptor{

	static Map<String,Long> userLastMilliSecond = new HashMap<>();
	public static final Logger logger = LoggerFactory.getLogger(AccessInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		String method =request.getRequestURI();
		String clientIp = HttpUtil.getClientIp(request);
		String key = clientIp+method;
		
		Long lastMilliSecond = userLastMilliSecond.get(key);
		long curMillis = System.currentTimeMillis();
		
		if(userLastMilliSecond.size()>100) {
			userLastMilliSecond.clear();
		}
		userLastMilliSecond.put(key, curMillis);
		if(lastMilliSecond!=null) {
			if(curMillis - lastMilliSecond <1000*2) {
				response.sendRedirect(request.getContextPath()+"/warn.html");
				return false;
			}
		}
		logger.info(clientIp+" is requesting url: "+method+" @ "+ DateUtil.date2Str(curMillis));
		return true;
	} 

}
